#!/bin/bash
#
# Copyright (C) 2025, Cyrus Li (e21920076@126.com). All rights reserved.
#

#
# # A simple utility to manage privoxy without using systemctl
# =============================================================================
#
# ## 1 Install package privoxy
# =============================================================================
# root# apt -y install privoxy
# root# systemctl disable privoxy
# root# chmod u+s /usr/sbin/privoxy
# hnli$ stat /usr/sbin/privoxy | grep Uid
# Access: (4755/-rwsr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
#
# ## 2 Create a config file
# =============================================================================
# hnli$ sudo cp /etc/privoxy/config ~/etc/privoxy/config
# hnli$ vi ~/etc/privoxy/config
# hnli$ sudo diff -u /etc/privoxy/config ~/etc/privoxy/config
# .....<snip>............................................................
# -listen-address  127.0.0.1:8118
# -listen-address  [::1]:8118
# +listen-address  192.168.10.54:8181
# +listen-address  [::1]:8181
# .....<snip>............................................................
#
# ## 3 Start privoxy
# =============================================================================
# hnli$ privoxy --pidfile /tmp/proxy.pid --user privoxy ~/etc/privoxy/config
#
# ## 4 Configure on the client
# =============================================================================
# Open firefox on the client, and configure network settings as:
# [*] Manual proxy configuration
#     HTTP Proxy: 192.168.10.54 Port: 8181
#     [*] Also use this proxy for HTTPS
# No proxy for:
#     .com, .net, .edu, .cn, .org, 127.0.0.1/8, ::1
# [*] Proxy DNS when using SOCKS v5
#
# For more about using privoxy, please visit:
#     vcodehub/howto/1013.md
#

FILE=$(readlink -f "${BASH_SOURCE[0]}")
CDIR=$(dirname "$FILE")
NAME=$(basename "$FILE")

[[ $(hostname) == "HBri721" ]] && echo "Oh, no! It is a laptop!!!" && exit 1

HOME=$(echo ~)
F_CONFIG=${PROXY_CONFIG:-"$HOME/etc/privoxy/config"}
F_BIN=${PROXY_BIN:-"/usr/sbin/privoxy"}
F_PID=${PROXY_PID:-"/tmp/.privoxy.pid"}

function proxy_show
{
    ps -ef | grep $F_BIN | grep -v grep
    return $?
}

function proxy_stop
{
    # XXX: sudo is required
    [[ -f $F_PID ]] && sudo kill -9 $(cat $F_PID)
    sudo rm -f $F_PID
}

function proxy_start
{
    $F_BIN --pidfile $F_PID --user privoxy $F_CONFIG
}

subcmd=${1:-"help"}
bin_name=$(basename $F_BIN)
rc=0
case $subcmd in
show)
    proxy_show
    if (( $? != 0 )); then
        echo "Oops, $bin_name is not running." >&2
        rc=1
    fi
    ;;
stop)
    proxy_stop
    ;;
start)
    proxy_show && echo "$bin_name is running" && exit 0
    proxy_start
    proxy_show
    if (( $? != 0 )); then
        echo "Oops, failed to start $bin_name." >&2
        rc=1
    else
        echo "Nice, $bin_name is started."
    fi
    ;;
*)
    echo "$NAME: <show|start|stop>" >&2
    rc=1
    ;;
esac

exit $rc
